package com.lh.config;

import com.lh.auth.AuthFailHandler;
import com.lh.auth.AuthSuccessHandler;
import com.lh.auth.AuthUserDetailsServiceImpl;
import com.lh.auth.UsernamePassAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    final AuthUserDetailsServiceImpl userDetails;
//    final AuthSuccessHandler authSuccessHandler;
//    final AuthFailHandler authFailHandler;
//
//    public SecurityConfig(AuthUserDetailsServiceImpl userDetails, AuthSuccessHandler authSuccessHandler, AuthFailHandler authFailHandler) {
//
//        this.userDetails = userDetails;
//        this.authSuccessHandler = authSuccessHandler;
//        this.authFailHandler = authFailHandler;
//    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略请求，不经过security过滤器链
        web.ignoring().mvcMatchers(HttpMethod.GET, "/**");
    }

    /**
     * 从容器中取出 AuthenticationManagerBuilder，执行方法里面的逻辑之后，放回容器
     *
     * @param authenticationManagerBuilder x
     * @throws Exception
     */
    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
//        authenticationManagerBuilder.userDetailsService(userDetails).passwordEncoder(new BCryptPasswordEncoder());
    }

//    @Override
//    public void configure(HttpSecurity http) throws Exception {
//        //解决跨域问题。cors 预检请求放行,让Spring security 放行所有preflight request（cors 预检请求）
//        http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
//        //让Security永远不会创建HttpSession，它不会使用HttpSession来获取SecurityContext
//        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//                .and().headers().cacheControl();
//        http.authorizeRequests()
//                .antMatchers("/admin/**")
//                .hasAuthority("root")
//                .antMatchers("/").permitAll();
//       //登陆
//        http.addFilterAt(myUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
//        //处理异常情况：认证失败和权限不足
//        http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
//            response.getWriter().println("认证失败");
//        }).accessDeniedHandler((request, response, accessDeniedException) -> {
//            response.getWriter().println("你的权限不足以访问该资源");
//        });
//    }


    /**
     * 登陆拦截器
     *
     * @return
     * @throws Exception
     */
//    @Bean
//    public UsernamePassAuthenticationFilter myUsernamePasswordAuthenticationFilter() throws Exception {
//        UsernamePassAuthenticationFilter filter = new UsernamePassAuthenticationFilter();
//        //成功后处理
////        filter.UsernamePasswordAuthenticationFilter(authSuccessHandler);
////        //失败后处理
////        filter.UsernamePasswordAuthenticationFilter(authFailHandler);
////        filter.UsernamePasswordAuthenticationFilter(authenticationManagerBean());
//        return filter;
//    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 定义认证规则
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                .withUser("zhangsan").password("123456").roles("VIP1", "VIP2")
                .and()
                .withUser("lisi").password("123456").roles("VIP2")
                .and()
                .withUser("wangwu").password("123456").roles("VIP3");
    }
}

